/*
 * Created by Federico Pisarello - SisDev Software (c) 2013 - fpisarello@sisdevsoft.com
 */
var popFotoForm = 'articulosFotoPop.php';
var popForm = 'articulosPop.php';
var actionForm = 'articulosAction.php';

var joDataArticulos;
var oTable;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var action = undefined;

var insumos;
var unidades;
var joImagen;

function $_init()
{	
	var gaiSelected;
	
	$(document).ready(function() {
    	oTable = $('#dt_articulos').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bAutoWidth": false,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?accion=search",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null
					  		]

				});
    	
    	$('#dt_articulos tbody td img').live( 'click', function () {
    		var nTr = $(this).parents('tr')[0];
    		if (oTable.fnIsOpen(nTr) )
    		{
    			/* This row is already open - close it */
    			this.src = "images/details_open.png";
    			oTable.fnClose( nTr );
    		}
    		else
    		{            
    			/* Open this row */            
    			this.src = "images/details_close.png";            
    			oTable.fnOpen( nTr, fnFormatDetailsArticulo(oTable, nTr), 'details' );        
    		}    
    	});
    	
    	/* Click event handler */
    	$('#dt_articulos tbody tr').live('click', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	        }
	        else {
	            oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$("#articulosDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:650, 
		modal: true,
		resizable: false,
		closeOnEscape: false,
		position : ['center',2],		
		dialogClass:'no-close',
		beforeClose: function() { $_ClearArticulosPopForm(); },
		open: function() {
			$('#articulosDialog').css('background-color','#4f4233');
		}
	});
		
	//Add Click for All Buttons in Search Form
	$("#btnAgregar").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEditar').click( function(e) {
		editProxyShow();
	});
	
	$('#btnEliminar').click( function(e) {
		delProxyShow();
	});	
}

function fnFormatDetailsArticulo(oTableArticulo, nTr){
	var aData = oTableArticulo.fnGetData(nTr);
	var sOut = "";
	var paramData =  "accion=searchArticuloDetalle&idArticulo=" + aData[0];
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
        async: false,
		dataType: 'html',
        success: function(strHtml)
                            {
        						sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
        						sOut += strHtml;
        						sOut += '</table>';
                            }
    });
		
	return sOut;
}

function $_initPop()
{
	//Add Click for All Buttons in Pop Form
	$('#btnCerrar').click( function(e) {
		$('#articulosDialog').dialog('close');
	});
	$('#btnGuardar').click( function(e) {
		$('#articulosPopForm').submit();
	});
	
	//Foto
	$('#btnCargar').click( function(e) {
		$('#imageFile').click();
	});
	$('#btnVer').click( function(e) {
		$('#articulosFotoDialog').load(popFotoForm).dialog('open');
	});
	
	$('.numeric').numeric();
	
	insumos = new Array();
	unidades = new Array();
	
	var idUnidadCompra;
	var idAlicuota;
	
	joImagen = undefined;

	//Populate Articulo Data	
	if(action == iConst.EDIT)
	{
		$('#codProducto').val(joDataArticulos.codProducto);
		$('#grupoProducto').val(joDataArticulos.grupoProducto);
		$('#nombreFacturacion').val(joDataArticulos.nombreFacturacion);
		idUnidadCompra = joDataArticulos.idUnidadCompra;
		$('#precio').val(joDataArticulos.precio);
		$('#mtsPieza').val(joDataArticulos.mtsPieza);
		idAlicuota = joDataArticulos.idAlicuota;
		joImagen = joDataArticulos.foto;
		
		$.each(joDataArticulos.articulosVariedades, function (index, item) {
			var idVariedad = item.variedad.replace('#',''); 
			$('.'+idVariedad).prop('checked', true);
			$('.'+idVariedad).attr('disabled', true);
			$('.can'+idVariedad).val(item.cantidad);
			$('.can'+idVariedad).attr('disabled', true);
		});
				
		for(var i=1;i<=10;i++) {
				insumos[i] = new $_autoCompleteHelper({
					dataMode: 'remote',
					editMode: action,
					control: 'insumo' + i,
					action: actionForm + '?accion=getInsumos',
					id: (joDataArticulos ? joDataArticulos['idInsumo'+i] : valueConst.NULL_VALUE),
					text: (joDataArticulos ? joDataArticulos['descInsumo'+i] : valueConst.NULL_STRING)
				});
				
				unidades[i] = new $_autoCompleteHelper({
					dataMode: 'remote',
					editMode: action,
					control: 'unidad' + i,
					action: actionForm + '?accion=getUnidadesMedida',
					id: (joDataArticulos ? joDataArticulos['idUnidad'+i] : valueConst.NULL_VALUE),
					text: (joDataArticulos ? joDataArticulos['descUnidad'+i] : valueConst.NULL_STRING)
				});
				
				if(joDataArticulos['idInsumo'+i] != undefined)
					$('#cantidad'+i).val(joDataArticulos['cantidad'+i]);
		}
	}
	else if(action == iConst.NEW) {		
		for(var i=1;i<=10;i++) {
			insumos[i] = new $_autoCompleteHelper({
				dataMode: 'remote',
				editMode: action,
				control: 'insumo' + i,
				action: actionForm + '?accion=getInsumos'
			});
			
			unidades[i] = new $_autoCompleteHelper({
				dataMode: 'remote',
				editMode: action,
				control: 'unidad' + i,
				action: actionForm + '?accion=getUnidadesMedida'
			});
		}
	}
	
	$_ValidatorSetDefaults();
	$_initPopValidator();
	
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'accion=getUnidadesMedidaArticulo', 
	    dataType: 'json', 
	    success: function(json) {
	    	$('#cmbUnidadCompra').append($('<option selected>').text('...').attr('value', ''));
	        $.each(json, function(i, value) {
	        	if(value.idUnidadMedida == idUnidadCompra)
	        		$('#cmbUnidadCompra').append($('<option selected>').text(value.descripcion).attr('value', value.idUnidadMedida));
	        	else
	        		$('#cmbUnidadCompra').append($('<option>').text(value.descripcion).attr('value', value.idUnidadMedida));
	        });
	    }
	});	
	
	//Alicuotas
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'accion=getAlicuotas', 
	    dataType: 'json', 
	    success: function(json) {
	    	$('#cmbAlicuota').append($('<option selected>').text('...').attr('value', ''));
	        $.each(json, function(i, value) {
	        	if(value.idAlicuota == idAlicuota)
	        		$('#cmbAlicuota').append($('<option selected>').text(value.valor+' %').attr('value', value.idAlicuota));
	        	else
	        		$('#cmbAlicuota').append($('<option>').text(value.valor+' %').attr('value', value.idAlicuota));
	        });
	    }
	});
	
	$('#imageFile').change( function() {

		var fr = new FileReader();

	    fr.onload = function() {
	        var img = new Image;
	        var canvas = document.createElement('canvas');
	        var ctx=canvas.getContext("2d");
	        img.onload = function() {
	            canvas.width=img.width;
	    		canvas.height=img.height;
	            ctx.drawImage(img, 0, 0, img.width, img.height);
	            
	            joImagen = canvas.toDataURL();
	        }
	        img.src = fr.result;  
	    };
	    
	    fr.readAsDataURL(this.files[0]);
	});
	
	$("#articulosFotoDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:830,
		modal: true,
		resizable: false,
		closeOnEscape: false,
		position : ['center',2],		
		dialogClass:'no-close',
		beforeClose: function() { $_ClearArticulosFotoPopForm(); },
		open: function() {
			$('#articulosFotoDialog').css('background-color','#4f4233');
		}
	});
}

function addProxyShow()
{
	//Reset State of action and IndexPK
	actionPK = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	$('#articulosDialog').load(popForm).dialog('open');
}

function editProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', 'Seleccione un Articulo de la Grilla');
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "accion=" + iConst.EDIT + "&idArticulo=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataArticulos = jsonObj;
        						//Open Pop Dialog
        						$('#articulosDialog').load(popForm).dialog('open');
                            }
        });
	
return true;
}

function $_saveArticulos(action)
{
	$("#btnGuardar").attr('disabled','disabled');
	
	var paramData = 'accion=addOrEdit&' + $("#articulosPopForm").serialize();
	
	for(var i=1;i<=10;i++) {
		if(insumos[i].id != undefined) {
			paramData += '&insumo' + i + '=' + insumos[i].id;
			paramData += '&unidad' + i + '=' + unidades[i].id;
			paramData += '&cantidad' + i + '=' + $('#cantidad'+i).val();
		}
	}
	
	paramData += "&joImagen=" + encodeURIComponent(JSON.stringify(joImagen))
	
	if(action == iConst.EDIT)
		paramData += '&idArticulo=' + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#articulosDialog').dialog('close');
				oTable.fnStandingRedraw();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
            $("#btnGuardar").removeAttr('disabled');
        }
    });

return true;
}

function delProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', 'Seleccione un Articulo de la Grilla');
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deleteArticulosDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#deleteArticulosDialog').css('background-color','#4f4233');
			$('#btnConfirmaEliminar').click( function(e) {
				$_del();
			});
			$('#btnSalirEliminar').click( function(e) {
				$('#deleteArticulosDialog').dialog('close')
			})
		}
	});
	$('#deleteArticulosDialog').dialog('open');	
}

function $_del()
{
	var paramData = 'accion=' + action + '&idArticulo=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){
										$_showMessage('OK', 'OK', jsonObj.msg);
										
										//Reset State of action and IndexPK
										actionPK = undefined;
										action = iConst.NEW;
										oTable.fnStandingRedraw();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deleteArticulosDialog').dialog('close');
                                }
            });

return true;
}

function $_initPopValidator()
{
	$('#articulosPopForm').validate({
		submitHandler: function() {
			$_saveArticulos(action);
		}, 		
		rules: {
			codProducto: {required: true,minlength: 1},
			grupoProducto: {required: true,minlength: 1},
			nombreFacturacion: {required: true,minlength: 1},
			cmbUnidadCompra: {required: true,minlength: 1},
			precio: {required: true,minlength: 1},
			mtsPieza: {required: true,minlength: 1},
			cmbAlicuota: {required: true,minlength: 1}
		},
		messages: {
			codProducto: {required: '',minlength: ''},
			grupoProducto: {required: '',minlength: ''},
			nombreFacturacion: {required: '',minlength: ''},
			cmbUnidadCompra: {required: '',minlength: ''},
			precio: {required: '',minlength: ''},
			mtsPieza: {required: '',minlength: ''},
			cmbAlicuota: {required: '',minlength: ''}
		}
	});
}

function $_ClearArticulosPopForm()
{	
	$("#articulosDialog").empty();
}

function $_ClearArticulosFotoPopForm()
{
	$("#articulosFotoDialog").empty();
}